package com.czmh.etc.onlinepubsys.interceptors;

import com.alibaba.fastjson.JSONObject;
import com.czmh.etc.onlinepubsys.utils.IpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * 日志打印拦截器
 */
public class LogInterceptor implements HandlerInterceptor {
    private static Logger logger= LoggerFactory.getLogger(WebMvcConfigurationSupport.class);
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        //clientIp
        String clientIp = IpUtil.getIpAddress(httpServletRequest);
        StringBuilder builder = new StringBuilder(httpServletRequest.getRequestURL());
        logger.info(clientIp + " Request URL[" + httpServletRequest.getMethod() + "]: " + builder.toString());
        //获取请求参数
        Enumeration em = httpServletRequest.getParameterNames();
        JSONObject params = new JSONObject();
        while (em.hasMoreElements()) {
            String name = (String) em.nextElement();
            String value = httpServletRequest.getParameter(name);
            params.put(name,value);
        }
        logger.info("Params:" + params);
        return true;
    }
 
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }
 
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}